package com.ruoyi.project.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.IStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 学生Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-10-07
 */
@Service
public class StudentServiceImpl implements IStudentService
{

    private static final Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CollegeStaffMapper collegeStaffMapper;

    @Autowired
    private CollegeMapper collegeMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;



    /**
     * 查询学生
     * 
     * @param id 学生ID
     * @return 学生
     */
    @Override
    public Student selectStudentById(Integer id)
    {
        return studentMapper.selectStudentById(id);
    }

    /**
     * 查询学生列表
     * 
     * @param student 学生
     * @return 学生
     */
    @Override
    public List<Student> selectStudentList(Student student)
    {
        return studentMapper.selectStudentList(student);
    }

    /**
     * 新增学生
     * 
     * @param student 学生
     * @return 结果
     */
    @Override
    public int insertStudent(Student student, SysUser sysUser)
    {
       if(studentMapper.selectStudentByUserIdcard(student.getIdcardCode()).size() != 0){
           throw new CustomException("学生身份证已存在");
       }
        //当前用户的院校id
        College college = collegeMapper.selectCollegeById(sysUser.getDeptId().intValue());
        if(college==null){
            throw new CustomException("系统暂无查询到当前院校代码");
        }

        student.setCreateTime(new Date());
        student.setCollegeId(college.getCollegeId());
        student.setCollegeCode(college.getCollegeCode());
        student.setCollegeName(college.getCollegeName());

        return studentMapper.insertStudent(student);
    }


    /**
     * 导入学生
     *
     * @param student 学生
     * @return 结果
     */
    public int importStudent(Student student)
    {
        return studentMapper.insertStudent(student);
    }


    /**
     * 修改学生
     * 
     * @param student 学生
     * @return 结果
     */
    @Override
    public int updateStudent(Student student)
    {

        Student student_ = studentMapper.selectStudentByUserIdcard(student.getIdcardCode()).get(0);
        if(!student.getId().equals(student_.getId())){
            throw new CustomException("学生身份证已存在");
        }
        return studentMapper.updateStudent(student);
    }

    /**
     * 批量删除学生
     * 
     * @param ids 需要删除的学生ID
     * @return 结果
     */
    @Override
    public int deleteStudentByIds(Integer[] ids)
    {
        return studentMapper.deleteStudentByIds(ids);
    }

    /**
     * 删除学生信息
     * 
     * @param id 学生ID
     * @return 结果
     */
    @Override
    public int deleteStudentById(Integer id)
    {

        Student student = studentMapper.selectStudentById(id);
        memberMapper.deleteMemberById(student.getMemberId().intValue());
        return studentMapper.deleteStudentById(id);
    }


    /**
     * 导入用户数据
     *
     * @param studentList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importCollege(List<Student> studentList, boolean isUpdateSupport,SysUser sysUser) {
        if (StringUtils.isNull(studentList) || studentList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Student student : studentList)
        {
            try
            {
                //当前用户的院校id
                College college = collegeMapper.selectCollegeByCode(student.getCollegeCode());
                if(college==null){
                    throw new CustomException("系统暂无查询到当前院校代码");
                }
                // 验证是否存在这个用户
               List<Student> u = studentMapper.selectStudentByUserIdcard(student.getIdcardCode());
                if (u.size()==0)
                {

                    student.setCreateTime(new Date());
                    student.setCollegeId(college.getCollegeId());

                    student.setGender((student.getGender()));

                    this.importStudent(student);


                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getRealName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    student.setUpdateTime(new Date());
                    student.setCollegeId(college.getCollegeId());
                    student.setCollegeCode(college.getCollegeCode());
                    this.importStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getRealName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生 " + student.getRealName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学生 " + student.getRealName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 插入用户对象
     * @param user
     * @return
     */
    public int insterSysUser(SysUser user){

       return   sysUserMapper.insertUser(user);

    }

    @Override
    public Student selectStudentByMemberId(int member_id) {
        return studentMapper.selectStudentByMemberId(member_id);
    }

    @Override
    public Integer updateMemberIdByIdCard(String idCard, int memberId){
        return studentMapper.updateMemberIdByIdCard(idCard,memberId);
    }

    @Override
    public Student getStudentByUserId(Long userId){
        return studentMapper.getStudentByUserId(userId);
    }

    @Override
    public SysUser getUserByIdCardName(String idCard,String name){
        Student student = new Student();
        student.setIdcardCode(idCard);
        student.setRealName(name);
        List<Student> students = studentMapper.selectStudentListUser(student);
        if(students==null||students.size()==0){
            throw new CustomException("系统暂无查询到当前用户");
        }
        return sysUserMapper.selectUserById(students.get(0).getUserId());
    }

    @Override
    public int updateStudentWx(Student student) {
        return studentMapper.updateStudent(student);
    }

}
